<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once("Core.php");

class CI_Staff extends CI_Core{
	function __construct(){
		parent::__construct();
		$this->database('default');
	} 
	//删除员工员工
	public function remove(){
		$this->db->where_in('id', explode(',',$this->ci->input->post('id')));
		$this->db->delete('admin');
	}
	//保存员工
	public function save(){
		$row = array(
			'role_id'=> $this->ci->input->post('role_id'),
			'email' => $this->ci->input->post('email'),
			'alias' => $this->ci->input->post('alias'),
			'is_config_menu'=>$this->ci->input->post('is_config_menu'),
		);
		if(!$this->ci->input->post('id')){
			$row['username']=$this->ci->input->post('username');
			$row['password']=md5($this->ci->input->post('password'));
			$a=$this->get_one('id',array('username'=>$this->ci->input->post('username')),'admin');
			if($a!=array()) exit('{"status":"ERROR","msg":"此管理员已存在!"}');
		}
		if($this->ci->input->post('password')){
			if($this->ci->input->post('password')!=$this->ci->input->post('conf_pwd')) exit('{"status":"ERROR","msg":"两次密码输入不一致!"}');
			$row['password']=md5($this->ci->input->post('password'));
		}
		$row['scope_site']=implode(',', $this->ci->input->post('scope_site'));

		$top_menu    = $this->ci->input->post('top_menu');
		$sub_menu    = $this->ci->input->post('sub_menu');
		$act=array();
		foreach($top_menu as $k=>$v){
			foreach($v as $i=>$s){
				foreach($sub_menu[$k][$s] as $e=>$o){
					$act[$k][$s][$e]=$o;
				}
			}
		}
		$row['privileges']=json_encode($act);
		$this->write($row,'admin');
	}
	//获取员工
	public function getuser($tj=array(),$tjarr=array()){
		$this->open('admin');
		$data=$this->get_list($tj,$tjarr);
		$arr=array();
		foreach($data['result'] as $v){
			$a = $this->get_one('name',array('id'=>$v['role_id']),'admin_role');
			$v['role_name']=$a['name'];
			$arr[]=$v;
		}
		ob_clean();
		$rs = array('total'=>$data['total_rows'],'rows'=>$arr);
	    return $this->status(true, $rs);
	}
	
	//员工登录
	public function login(){
		$resp = array();
		$username = $this->ci->input->post('username');
		$password = $this->ci->input->post('password');
		$resp['submitted_data'] = $_POST;
		$login_status = 'invalid';
		$rs=$this->get_one('*',array('username'=>$username),'admin');
		if($rs==array()) return $this->status(true,array('login_status'=>'invalid','redirect_url'=>'.'));
		if($rs['password']==md5($password)){
			$this->ci->session->set_userdata('admin_name',$rs['username']);
			$this->ci->session->set_userdata('admin_id',$rs['id']);
			$this->ci->session->set_userdata('role_id',$rs['role_id']);
			$a=$this->get_one('id,name,sn',array('id'=>$rs['active_site']),'site');
			$this->ci->session->set_userdata('wechat_id',$a['id']);
			$this->ci->session->set_userdata('wechat_name',$a['name']);
			$this->ci->session->set_userdata('sn',$a['sn']);
			$this->ci->session->set_userdata('login',true);
			$b=$this->get_one('id',array('admin_id'=>$rs['id']),'service');
			if($b['id']) $this->ci->session->set_userdata('op',$b['id']);
			return $this->status(true,array('login_status'=>'success','redirect_url'=>'.'));
		}
		return $this->status(true,array('login_status'=>'invalid','redirect_url'=>'.'));
	}
	
	//保存员工级别及权限
	public function saverole(){
		$row['name'] = $this->ci->input->post('name');
		$row['pid'] = $this->ci->input->post('pid');
		$top_menu    = $this->ci->input->post('top_menu');
		$sub_menu    = $this->ci->input->post('sub_menu');
		$act=array();
		foreach($top_menu as $k=>$v){
			foreach($v as $i=>$s){
				foreach($sub_menu[$k][$s] as $e=>$o){
					$act[$k][$s][$e]=$o;
				}
			}
		}
		$row['privileges']=json_encode($act);
		$this->write($row,'admin_role');
	}
	//员工列表
	public function getlist(){
		$rs = $this->get_all('*',array(),'admin');
		return $this->status(true,$rs);
	}
	//角色列表
	public function getroles($root='0'){
		if($root!='0'){
			$arr=array($root);
			$this->getSubCategory($root,$arr,'pid','admin_role');
		}
		$rs = $this->get_all('*',array(),'admin_role',
		array(
		  'wherein'=>array('pid'=>$arr),
		  'orwhere'=>array('id'=>$this->ci->session->userdata('role_id')
		)));
		$this->open('admin');
		foreach($rs as $k=>$v){
			$log=array($v['id']);
			$this->getSubCategory($v['id'],$log,'pid','admin_role');
			$rs[$k]['count']=$this->count_rows(array(),//array('conditions'=>array('role_id'=>$v['id'])), 
			array(
		  		'wherein'=>array('role_id'=>$log),
			));
		}
		return $this->status(true,$rs);
	}
	//角色树
	public function roletree(){
		$pid = $this->ci->input->get('pid');
		$self = $this->ci->input->get('self');
		$params = array('pid'=>empty($pid)?"'0'":$pid);
		if($self) $params['id !=']=$self;
		$arr = $this->get_all('*',$params,'admin_role');
		$rs=array();
		foreach($arr as $v){
			$a = $this->get_all('id',array('pid'=>$v['id']),'admin_role');
			$rs[]=array(
				'id'=>$v['id'],
				'label'=>$v['name'],
				'branch'=>array(),
				'inode'=>count($a)>0?true:false
			);
		}
		return $this->status(true, $rs);
	}
	
	//获取角色信息
	public function roleinfo($id=''){
		if(empty($id)) return $this->status(false, array());
		$rs = $this->get_one('*',array('id'=>$id),'admin_role');
		return $this->status(true,$rs);
	}
	//删除角色
	public function delRole(){
		$rid=$this->ci->input->post('id');
		$log=array($rid);
		$this->getSubCategory($rid,$log,'pid','admin_role');
		$this->db->where_in('role_id', $log);
		$this->db->delete('admin');
		
		$this->db->where_in('id', $log);
		$this->db->delete('admin_role');
		echo '{"status":"OK","msg":"执行成功"}';
	}
	//获取员工资料
	public function info($id=''){
		if(empty($id)) return $this->status(false, array());
		$rs = $this->get_one('*',array('id'=>$id),'admin');
		return $this->status(true,$rs);
	}
	//修改密码 
	public function changepwd(){
		$old=$this->ci->input->post('password');
		$new_pw_edit=$this->ci->input->post('new_pw_edit');
		$pwd_confirm_edit=$this->ci->input->post('pwd_confirm_edit');
		$id=$this->ci->session->userdata('admin_id')?$this->ci->session->userdata('admin_id'):$this->ci->input->post('admin_id');
		$rs=$this->get_one('id,password',array('id'=>$id),'admin');
		if($rs==array()) return $this->status(1, '');
		if($rs['password']!=md5($old)) return $this->status(2, '');
		if($new_pw_edit!=$pwd_confirm_edit) return $this->status(3, '');
		$this->db->update('admin',array('password'=>md5($new_pw_edit)),array('id'=>$id));
		return $this->status('OK', '');
	}
	//根据部门获取员工
	public function getRoleStaff($id){
		$arr=array($id);
		$this->getSubCategory($id,$arr,'pid','admin_role');
		
		$rs = $this->get_all('*',array(),'admin',array('wherein'=>array('role_id'=>$arr)));
		return $this->status(true,$rs);
	}
	//获取部门权限
	public function getPrivileges($type,$id,&$data){
		$public_auth = json_decode(file_get_contents('static/data/public_menu.json'),true);
		$pc_auth     = json_decode(preg_replace("/\\s/is",'',file_get_contents('static/data/pc_menu.json')),true);
		$wechat_auth = json_decode(preg_replace("/\\s/is",'',file_get_contents('static/data/wechat_menu.json')),true);
		$app_auth    = json_decode(preg_replace("/\\s/is",'',file_get_contents('static/data/app_menu.json')),true);
		$market_auth = json_decode(preg_replace("/\\s/is",'',file_get_contents('static/data/market_menu.json')),true);
		$rs          = $this->get_one('*',array('id'=>$id),'admin_role');
		if($rs['pid']=='0'&&$type=='EDIT'){
			$data['public_auth']= json_encode($public_auth);

		}else{
			$rs = $this->get_one('*',array('id'=>$id==1?1:$rs['pid']),'admin_role');
			$rs = json_decode($rs['privileges'],true);
			$data['public_auth']= json_encode($this->_filterPrivileges($public_auth,$rs,'public'));
		}	
	}
	private function _filterPrivileges($arr,$rs,$key){
		foreach($arr as $k=>$v){
			if(!in_array($v['en_name'], array_keys($rs[$key]))){
				unset($arr[$k]);
				continue;
			} 
			foreach($v['submenu'] as $i=>$s){
				if(!in_array($s['en_name'],array_keys($rs[$key][$v['en_name']]))){
					unset($arr[$k]['submenu'][$i]);
					continue;
				}
				$a = explode(',',$s['auth']);
				foreach($a as $t=>$o){
					if(!in_array($o, $rs[$key][$v['en_name']][$s['en_name']])) unset($a[$t]);
				}
				$arr[$k]['submenu'][$i]['auth']=implode(',',$a);
			}
		}
		return $arr;
	}
	//检查控制器权限
	public function checkCtrlAuth($id,$name,$auth){
		if(!$id||!$name||!$auth) exit('Parameter Error!');
		$rs = $this->get_one('role_id,privileges',array('id'=>$id),'admin');
		$this->getPrivileges('ADD',$rs['role_id'],$data);
		$this->_checkCtrlAuth('public',$data['public_auth'],$rs['privileges'],$name,$auth);
		//$this->_checkCtrlAuth('pc',$data['pc_auth'],$rs['privileges'],$name,$auth);
		//$this->_checkCtrlAuth('wechat',$data['wechat_auth'],$rs['privileges'],$name,$auth);
		//$this->_checkCtrlAuth('app',$data['app_auth'],$rs['privileges'],$name,$auth);
		//$this->_checkCtrlAuth('market',$data['market_auth'],$rs['privileges'],$name,$auth);
	}
	private function _checkCtrlAuth($key,$arr,$pr,$name,$auth){
		$pr = json_decode($pr,true);
		foreach(json_decode($arr,true) as $k=>$v){
			foreach($v['submenu'] as $s){
				if($s['en_name']==$name){
					$current = array();
					foreach($pr[$key] as $i=>$t){ 
						if(in_array($name,array_keys($t))){
							foreach($pr[$key][$i][$s['en_name']] as $o){
								if(in_array($o, explode(',',$s['auth']))) $current[]=$o;
							}
						}
					}
					if(!in_array($auth,$current)) exit('<div class="alert alert-danger"><b>您没有权限进行此操作！</b></div>'); 
				}
			}
		}
	}
}